<template>
  <div>
    <el-form ref="deptForm" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select
          v-model="form.manager"
          style="width:80%"
          placeholder="请选择"
        >
          <el-option
            v-for="item in employees"
            :key="item.id"
            :value="item.username"
            :label="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="Hsubimt">确定</el-button>
        <el-button size="small" @click="$emit('colde')">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getEmployees } from '@/api/employees'
import { addData, getDataget } from '@/api/department'
import { putData } from '@/api/department'
export default {
  name: 'VueHrDeptDialog',

  props: {
    id: {
      required: true,
      type: String
    },

    edit: {
      required: true,
      type: Boolean
    },

    originList: {
      required: true,
      type: Array
    }

  },

  data() {
    // 校验部门编码
    const validCode = (rule, value, callback) => {
      let isCode = this.originList.map(item => item.code)
      // console.log(isCode)
      // 编辑状态，先移除自己的编码
      if (this.edit) {
        isCode = this.originList.filter(item => item.id !== this.id).map(item => item.code)
      }
      if (isCode.includes(value)) {
        // 部门编码已存在就抛出错误
        callback(new Error(`部门编码 ${value} 已存在`))
      } else {
        callback()
      }
    }

    // 校验部门名称
    const validName = (rule, value, callback) => {
      let existNameList = this.originList.filter(item => item.id === this.id).map(item => item.name)
      if (this.edit) {
        const dept = this.originList.find(item => item.id === this.id)
        // 2. 取出pid(它的父级是谁)
        const pid = dept.pid
        // 3. 过滤： 同一个父级，不包括自己； map： 只要需要名字
        existNameList = this.originList.filter(item => item.pid === pid && item.id !== this.id).map(item => item.name)
      }
      // console.log(isName)

      if (existNameList.includes(value)) {
        callback(new Error(`部门名称 ${value} 已存在`))
      } else {
        callback()
      }
    }
    return {
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      rules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入部门编码', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '请输入部门负责人', trigger: ['blur', 'change'] }
        ],
        introduce: [
          { required: true, message: '请输入部门介绍', trigger: 'blur' },
          { min: 1, max: 300, message: '长度在 3 到 300 个字符', trigger: 'blur' }
        ]
      },
      employees: [] // 负责人列表
    }
  },

  // watch: {
  //   // 解决数据不更新的方式3
  //   // 使用 监听器。监听id的变化，发生变化时重新获取数据，填充到表单中
  //   'id': function(newVal, belVal) {
  //     this.lodeDataget()
  //   }
  // },

  created() {
    this.lodeEmployees()
    if (this.edit) {
      this.lodeDataget()
    }

    // console.log(this.originList, 'originList1111')
  },

  methods: {
    // 清空表单的校验规则和数据
    resetForm() {
      this.$refs.deptForm.resetFields()
    },
    // 获取负责人列表
    async  lodeEmployees() {
      try {
        const res = await getEmployees()
        // console.log(res)
        if (res.code === 10000) {
          this.employees = res.data
        }
      } catch (error) {
        console.log(error)
      }
    },
    // 获取当前（单个）部门信息
    async lodeDataget() {
      try {
        const res = await getDataget(this.id)
        // console.log(res, 'getDataget')
        // 将获取到的信息赋值 form 完成回显
        this.form = res.data
      } catch (error) {
        console.log(error)
      }
    },
    Hsubimt() {
      //  兜底校验
      this.$refs.deptForm.validate((valid) => {
        if (!valid) return // 校验失败
        //  判断是新增还是修改
        this.edit ? this.doEdit() : this.doAdd()
      })
    },
    // 新增请求
    async  doAdd() {
      try {
        const res = await addData({ ...this.form, pid: this.id })
        // console.log(res)
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        // 重新渲染数据，关闭弹层
        // 要用到子传父
        this.$emit('success')
      } catch (error) {
        // console.log(error)
        this.$message.error(error)
      }
    },
    // 修改
    async doEdit() {
      try {
        const res = await putData(this.form)
        // console.log(res)
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        // 重新渲染数据，关闭弹层
        // 要用到子传父
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    }

  }
}
</script>

<style lang="scss" scoped>

</style>

